import {
  getToken, setToken, removeToken, getUserCode, setUserCode, removeUserCode, getDataSource, setDataSource, removeDataSource,
} from '@/utils/auth';
import { verifyUser } from '@/utils/index';
import { loginByUsername } from '@/api/login';

const user = {
  state: {
    token: getToken(),
    // userId: '1001A210000000003ZTW', // 董宝元
    // userId: '0001A2100000000029BM', // 李雅倩
    // userId: '1001A210000000003W9K', // 杜明
    // userId: '1001A21000000000033F', // 耿少慧
    // userId: '1001A210000000000BA9', // 裴炎咯
    userId: verifyUser(), // 用户id
    // groupId: '0001A2100000000008PV',
    groupId: '', // 部门id
    userName: '', // 返回的用户姓名
    userCode: getUserCode(), // 用户编码 也就是用户输入的用户账号
    deptName: '', // 部门名称
    uap_dataSource: getDataSource(), // 数据源编码
    loginType: '1', // 登录类型
  },
  mutations: {
    SET_TOKEN: (state: any, token: any) => {
      state.token = token;
    },
    // SET_USERID: (state: any, userId: any) => {
    //   state.userId = userId;
    // },
    SET_GROUPID: (state: any, groupId: any) => {
      state.groupId = groupId;
    },
    SET_USERNAME: (state: any, userName: any) => {
      state.userName = userName;
    },
    SET_USERCODE: (state: any, userCode: any) => {
      state.userCode = userCode;
    },
    SET_DEPNAME: (state: any, deptName: any) => {
      state.deptName = deptName;
    },
    SET_DATASOURCE: (state: any, dataSource: any) => {
      state.uap_dataSource = dataSource;
    },
  },
  actions: {
    setSize({ commit }: any, size: any) {
      commit('SET_SIZE', size);
    },
    // 用户名登录
    LoginByUsername({ commit }: any, userInfo: any) {
      const userCode = userInfo;
      commit('SET_USERCODE', userCode);
      setUserCode(userCode);
      return new Promise((resolve, reject) => {
        loginByUsername(userCode).then((res: any) => {
          const data = res.data;
          console.log('data :', data);
          commit('SET_TOKEN', data.uap_token);
          // commit('SET_USERID', data.cuserid);
          commit('SET_GROUPID', data.pk_group);
          commit('SET_USERNAME', data.user_name);
          commit('SET_DEPNAME', data.deptName);
          commit('SET_DATASOURCE', data.uap_dataSource);
          setToken(data.uap_token);
          setDataSource(data.uap_dataSource);
          resolve('login 成功');
        }).catch((error: any) => {
          reject(error);
        });
      });
    },
    // 用户登出
    // 前端 登出
    FedLogOut({ commit }: any) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '');
        removeToken();
        removeUserCode();
        removeDataSource();
        resolve();
      });
    },
  },
};

export default user;
